package com.zzl.myblog.View.Activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.makeramen.roundedimageview.RoundedImageView;
import com.zzl.myblog.Bean.ResponseBean.UserBean;
import com.zzl.myblog.Bean.ViewBean.blog;
import com.zzl.myblog.R;
import com.zzl.myblog.Utils.HttpUtil;
import com.zzl.myblog.Utils.LogUtil;
import com.zzl.myblog.Utils.SqliteUtils;
import com.zzl.myblog.Utils.responseUtility;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class editUser extends AppCompatActivity {
    String TAG = "editUser";
    String oldUsername,age,sex;
    EditText username_et,age_et;
    RadioGroup radioGroup;
    Button save_btn,changeAvatar;
    String currentSex;
    RoundedImageView roundedImageView;

    private Uri imageUri;
    public static final int TACK_PHOTO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user);

        Intent intent = getIntent();
        oldUsername = intent.getStringExtra("username");
        initUI();
        initData();
    }

    private void initData() {
        // 访问server,填充当前的表单
        String url = "users";
        String params = "?username="+oldUsername;
        HttpUtil.user_GET("users", params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.i(TAG,"请求用户数据失败！"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try{
                    String json = response.body().string();
                    UserBean userBean = responseUtility.parse_user(json);
                    username_et.setText(oldUsername);
                    age_et.setText(userBean.getData().getAge());
                    for (int i = 0; i < radioGroup.getChildCount(); i++) {
                        RadioButton rd = (RadioButton) radioGroup.getChildAt(i); // 拿到男/女
                        if(rd.getText().equals(userBean.getData().getSex())){
                            rd.setChecked(true);
                            sendUpdate();
                            break;
                        }
                    }
                }catch (Exception e) {
                    LogUtil.i(TAG,"解析数据出错！"+e.getMessage());
                }
            }
        });
    }

    private void initUI() {
        username_et = findViewById(R.id.username);
        age_et = findViewById(R.id.age);
        radioGroup = findViewById(R.id.radioGroup);
        save_btn = findViewById(R.id.save);
        changeAvatar = findViewById(R.id.changeAvatar);
        roundedImageView = findViewById(R.id.avatar);

//        changeAvatar.setOnClickListener(v->{
//            File outputImage = new File(getExternalCacheDir(),"output_image.jpg");
//            try {
//                if(outputImage.exists()){
//                    outputImage.delete();
//                }
//                outputImage.createNewFile();
//            }catch (IOException e){
//                Log.i(TAG,e.getMessage());
//            }
//            if(Build.VERSION.SDK_INT >= 24){
//                imageUri = FileProvider.getUriForFile(editUser.this,"com.example.cameraalbumtest.fileprovider",outputImage);
//            }else{
//                imageUri = Uri.fromFile(outputImage);
//            }
//            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
//            startActivityForResult(intent,TACK_PHOTO);
//        });

        save_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 拿到选择的性别
                for (int i = 0; i < radioGroup.getChildCount(); i++) {
                    RadioButton rd = (RadioButton) radioGroup.getChildAt(i); // 拿到男/女
                    if (rd.isChecked()) {
                        currentSex = (String) rd.getText();
                        sendUpdate();
                        break;
                    }
                }
            }
        });
    }

    private void sendUpdate(){
        String currentAge = age_et.getText().toString();
        String CurrentUsername = username_et.getText().toString();

        Map<String, String> map = new HashMap<>();
        map.put("oldUsername", oldUsername);
        map.put("username", CurrentUsername);
        map.put("age", currentAge);
        map.put("sex", currentSex);

        String url = "users/update";
        // 提交用户信息到server
        HttpUtil.user_update_POST(url, map, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtil.i(TAG,"请求修改失败"+e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try{
                        String json = response.body().string();
                        UserBean userBean = responseUtility.parse_user(json);
                        Looper.prepare();
                        if(userBean.getStatus().equals("201")){
                            sendToast("修改成功!");
                            List<blog> blog = SqliteUtils.queryUser(oldUsername);
                            if(blog!=null){
                                blog.get(0).setUsername(CurrentUsername);
                                SqliteUtils.updateUsername(blog.get(0),oldUsername);
                            }
                            if(!oldUsername.equals(CurrentUsername)){
                                sendToast("请退出程序，重新登录哈!");
                            }
                        }else{
                            sendToast("修改失败了！");
                        }
                        Looper.loop();
                    }catch(Exception e){
                        LogUtil.i(TAG,"解析出错了"+e.getMessage());
                    }
                }
        });
    }
    private  void sendToast(String msg){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TACK_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));

                        // 放到RoundImageView控件中
                        roundedImageView.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        LogUtil.i(TAG, e.getMessage());
                    }
                }
                break;
            default:
                break;
        }
    }
}